package sam.jmsgserver.core;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class SendMsgTask implements Runnable{
	private Message msg;
	private Connection connection;

	public void run(){
		Server.logger.info("=> SendMsgTask.run()");
		
		if (this.msg!=null && this.msg.getBody()!=null){
			//send msg to others
			String from = this.msg.getFrom().split("/")[0];
			String strMsg = this.msg.getBody();
			
			Server.logger.info("from:"+from);
			Server.logger.info("msg:"+strMsg);
			
			
			
			for (RosterEntry entry : connection.getRoster().getEntries()){
				if (!from.equals(entry.getUser())){
					Chat chat = connection.getChatManager().createChat(entry.getUser(), null);
					try {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

						Message outMsg = new Message(this.msg.getFrom(), Message.Type.groupchat);
						outMsg.setBody("["+from+"] "+strMsg);
						
						Server.logger.info(
								">> to "+entry.getUser()+ "\r\n" +
								">> body="+outMsg.getBody() + "\r\n" +
								">> type="+outMsg.getType()
								);
						
						
						chat.sendMessage(outMsg);
						
					} catch (XMPPException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		Server.logger.info("<= SendMsgTask.run()");
	}
	
	public Message getMsg() {
		return msg;
	}

	public void setMsg(Message msg) {
		this.msg = msg;
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}
}
